<template>
  <div v-show="visible" class="modal-overlay">
    <div class="setup-modal" @click.stop>
      <div class="modal-header">
        <h2>游戏设置</h2>
      </div>

      <div class="modal-body">
        <!-- AI玩家手牌设置 -->
        <div class="setting-section">
          <h3>AI玩家手牌</h3>
          <div class="ai-cards-display">
            <div v-if="selectedAICards.length === 0" class="empty-state">
              点击下方按钮选择AI手牌
            </div>
            <div v-else class="selected-cards">
              <PokerCard
                v-for="card in selectedAICards"
                :key="card.id"
                :card="card"
                size="small"
                @click="removeAICard"
              />
            </div>
          </div>
          <button
            :class="[
              'btn',
              selectedAICards.length === 27 ? 'btn-success' : 'btn-primary',
            ]"
            @click="showAICardSelector"
          >
            选择AI手牌 ({{ selectedAICards.length }}/27)
            <span v-if="selectedAICards.length !== 27" class="required-hint"
              >必须27张</span
            >
          </button>
        </div>

        <!-- 级牌选择 -->
        <div class="setting-section">
          <h3>级牌设置 <span class="required-mark">*</span></h3>
          <div class="trump-card-display">
            <div v-if="!selectedTrumpCard" class="empty-state">
              请选择级牌 (必选)
            </div>
            <div v-else class="selected-trump">
              <PokerCard
                :card="selectedTrumpCard"
                size="medium"
                @click="clearTrumpCard"
              />
            </div>
          </div>
          <div class="trump-actions">
            <button
              :class="[
                'btn',
                selectedTrumpCard ? 'btn-success' : 'btn-primary',
              ]"
              @click="showTrumpCardSelector"
            >
              选择级牌
              <span v-if="!selectedTrumpCard" class="required-hint">必选</span>
            </button>
            <button
              v-if="selectedTrumpCard"
              class="btn btn-secondary"
              @click="clearTrumpCard"
            >
              清除级牌
            </button>
          </div>
        </div>

        <!-- 首次出牌玩家选择 -->
        <div class="setting-section">
          <h3>首次出牌玩家 <span class="required-mark">*</span></h3>
          <div v-if="selectedFirstPlayer === null" class="selection-hint">
            请选择首次出牌的玩家
          </div>
          <div class="player-selection">
            <div
              v-for="player in playerOptions"
              :key="player.id"
              :class="[
                'player-option',
                { active: selectedFirstPlayer === player.id },
              ]"
              @click="selectFirstPlayer(player.id)"
            >
              <div class="player-info">
                <div class="player-name">{{ player.name }}</div>
                <div class="player-position">座位号: {{ player.id }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button
          class="btn btn-success"
          :disabled="!canStartGame"
          @click="handleConfirm"
        >
          开始游戏
        </button>
        <button class="btn btn-secondary" @click="handleCancel">取消</button>
      </div>
    </div>

    <!-- AI手牌选择器 -->
    <CardSelector
      v-if="showAISelector"
      :visible="showAISelector"
      :multiple="true"
      :selected-cards="selectedAICards"
      :max-selection="27"
      isAi
      title="选择AI玩家手牌"
      @confirm="handleAICardsConfirm"
      @cancel="showAISelector = false"
    />

    <!-- 级牌选择器 -->
    <CardSelector
      v-if="showTrumpSelector"
      :visible="showTrumpSelector"
      :multiple="false"
      :selected-cards="selectedTrumpCard ? [selectedTrumpCard] : []"
      :is-level-card-selection="true"
      title="选择级牌"
      @confirm="handleTrumpCardConfirm"
      @cancel="showTrumpSelector = false"
    />

    <!-- 自定义确认对话框 -->
    <div
      v-if="showConfirmDialog"
      class="confirm-overlay"
      @click="showConfirmDialog = false"
    >
      <div class="confirm-dialog" @click.stop>
        <div class="confirm-header">
          <h3>🎮 确认游戏设置</h3>
        </div>
        <div class="confirm-body">
          <div class="confirm-section">
            <div class="confirm-label">AI手牌</div>
            <div class="confirm-value">
              已选择 {{ selectedAICards.length }} 张
            </div>
          </div>
          <div class="confirm-section">
            <div class="confirm-label">级牌</div>
            <div class="confirm-value">{{ selectedTrumpCard?.display }}</div>
          </div>
          <div class="confirm-section">
            <div class="confirm-label">首次出牌玩家</div>
            <div class="confirm-value">
              {{
                playerOptions.find((p) => p.id === selectedFirstPlayer)?.name
              }}
            </div>
          </div>
          <div class="confirm-warning">
            <div class="warning-icon">⚠️</div>
            <div class="warning-text">
              一旦开始游戏，本轮将无法重新修改AI手牌、级牌和首次出牌玩家，并且会结束上一轮的游戏。
            </div>
          </div>
          <div class="confirm-question">确定要开始游戏吗？</div>
        </div>
        <div class="confirm-footer">
          <button class="btn btn-success" @click="confirmStart">确定</button>
          <button class="btn btn-secondary" @click="showConfirmDialog = false">
            取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Card } from '../types/card'
import { GameConfig } from '../types/game'
import PokerCard from './PokerCard.vue'
import CardSelector from './CardSelector.vue'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'confirm', config: GameConfig): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const selectedAICards = ref<Card[]>([])
const selectedTrumpCard = ref<Card | null>(null)
const selectedFirstPlayer = ref<number | null>(null) // 默认不选择任何玩家
const showAISelector = ref(false)
const showTrumpSelector = ref(false)
const showConfirmDialog = ref(false)

// 玩家选项
const playerOptions = [
  { id: 0, name: 'AI玩家', position: 'bottom' },
  { id: 1, name: '玩家1', position: 'right' },
  { id: 2, name: '玩家2', position: 'top' },
  { id: 3, name: '玩家3', position: 'left' },
]

// 计算属性
const canStartGame = computed(() => {
  return (
    selectedAICards.value.length === 27 && // AI手牌必须是27张
    selectedTrumpCard.value !== null && // 级牌必须选择
    selectedFirstPlayer.value !== null && // 首次出牌玩家必须选择
    selectedFirstPlayer.value >= 0 &&
    selectedFirstPlayer.value <= 3
  )
})

// 方法
const showAICardSelector = () => {
  showAISelector.value = true
}

const showTrumpCardSelector = () => {
  showTrumpSelector.value = true
}

const handleAICardsConfirm = (cards: Card[]) => {
  // 验证卡牌数量
  if (cards.length !== 27) {
    alert('AI手牌必须选择27张牌！')
    return
  }

  // 验证卡牌ID是否有效（支持两副牌）
  const invalidCards = cards.filter((c) => {
    const id = c.id
    return !(
      (id >= 256 && id <= 268) || // 方块
      (id >= 512 && id <= 524) || // 梅花
      (id >= 768 && id <= 780) || // 红桃
      (id >= 1024 && id <= 1036) || // 黑桃
      id === 1037 ||
      id === 1294 || // 大小王
      (id >= 10256 && id <= 10268) || // 方块(第二副)
      (id >= 10512 && id <= 10524) || // 梅花(第二副)
      (id >= 10768 && id <= 10780) || // 红桃(第二副)
      (id >= 11024 && id <= 11036) || // 黑桃(第二副)
      id === 11037 ||
      id === 11294 // 大小王(第二副)
    )
  })

  if (invalidCards.length > 0) {
    console.error('选择的AI手牌包含无效ID:', invalidCards)
    alert(
      `选择的卡牌包含无效ID，请重新选择！\n无效卡牌: ${invalidCards.map((c) => `${c.display}(ID:${c.id})`).join(', ')}`
    )
    return
  }

  selectedAICards.value = [...cards]

  // 只有验证成功时才关闭选择器
  showAISelector.value = false
}

const handleTrumpCardConfirm = (cards: Card[]) => {
  selectedTrumpCard.value = cards.length > 0 ? cards[0] : null
  showTrumpSelector.value = false
}

const removeAICard = (card: Card) => {
  const index = selectedAICards.value.findIndex((c: Card) => c.id === card.id)
  if (index >= 0) {
    selectedAICards.value.splice(index, 1)
  }
}

const clearTrumpCard = () => {
  selectedTrumpCard.value = null
}

const selectFirstPlayer = (playerId: number) => {
  selectedFirstPlayer.value = playerId
}

const handleConfirm = () => {
  if (selectedAICards.value.length !== 27) {
    alert('AI手牌必须选择27张牌！')
    return
  }
  if (!selectedTrumpCard.value) {
    alert('请选择级牌！')
    return
  }
  if (selectedFirstPlayer.value === null) {
    alert('请选择首次出牌玩家！')
    return
  }
  if (!canStartGame.value) {
    alert('请完成游戏设置')
    return
  }

  // 显示自定义确认对话框
  showConfirmDialog.value = true
}

const confirmStart = () => {
  const config: GameConfig = {
    aiCards: selectedAICards.value,
    trumpCard: selectedTrumpCard.value!,
    firstPlayer: selectedFirstPlayer.value!,
    currentLevel: selectedTrumpCard.value?.rank || 0,
  }

  showConfirmDialog.value = false
  emit('confirm', config)
}

const handleCancel = () => {
  emit('cancel')
}

// 重置设置
const resetSettings = () => {
  selectedAICards.value = []
  selectedTrumpCard.value = null
  selectedFirstPlayer.value = null
  showAISelector.value = false
  showTrumpSelector.value = false
}

// 监听visible变化，每次打开弹框时重置所有设置
import { watch } from 'vue'
watch(
  () => props.visible,
  (newVisible: boolean) => {
    if (newVisible) {
      resetSettings()
    }
  }
)
</script>

<style scoped>
.setup-modal {
  background: white;
  border-radius: var(--border-radius-lg);
  padding: 0;
  width: 85%;
  max-height: 90vh;
  overflow: hidden;
  box-shadow: var(--shadow-lg);
  display: flex;
  flex-direction: column;
}

.modal-header {
  background: var(--poker-green);
  color: white;
  padding: var(--spacing-lg);
  text-align: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
}

.modal-body {
  padding: var(--spacing-lg);
  overflow-y: auto;
  flex: 1;
}

.setting-section {
  margin-bottom: var(--spacing-xl);
}

.setting-section h3 {
  color: var(--text-dark);
  font-size: 16px;
  margin-bottom: var(--spacing-md);
  border-bottom: 2px solid var(--poker-green);
  padding-bottom: var(--spacing-xs);
}

/* AI手牌显示 */
.ai-cards-display {
  min-height: 80px;
  border: 2px dashed #ccc;
  border-radius: var(--border-radius);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-md);
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-state {
  color: var(--text-light);
  font-style: italic;
}

.selected-cards {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-xs);
  justify-content: center;
}

/* 级牌显示 */
.trump-card-display {
  min-height: 100px;
  border: 2px dashed #ccc;
  border-radius: var(--border-radius);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-md);
  display: flex;
  align-items: center;
  justify-content: center;
}

.selected-trump {
  display: flex;
  justify-content: center;
}

.trump-actions {
  display: flex;
  gap: var(--spacing-sm);
  justify-content: center;
}

/* 玩家选择 */
.player-selection {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--spacing-sm);
}

.player-option {
  border: 2px solid #ddd;
  border-radius: var(--border-radius);
  padding: var(--spacing-md);
  cursor: pointer;
  transition: var(--transition);
  text-align: center;
}

/* 悬浮效果已删除 */

.player-option.active {
  border-color: var(--poker-green);
  background: var(--poker-light-green);
  color: white;
}

.player-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.player-name {
  font-weight: bold;
  font-size: 14px;
}

.player-position {
  font-size: 12px;
  opacity: 0.8;
}

.modal-footer {
  background: #f8f9fa;
  padding: var(--spacing-lg);
  display: flex;
  gap: var(--spacing-md);
  justify-content: center;
  border-top: 1px solid #dee2e6;
}

.modal-footer .btn {
  min-width: 100px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .setup-modal {
    max-width: 95vw;
    margin: var(--spacing-sm);
  }

  .modal-body {
    padding: var(--spacing-md);
  }

  .player-selection {
    grid-template-columns: 1fr;
  }

  .selected-cards {
    gap: 2px;
  }

  .trump-actions {
    flex-direction: column;
    align-items: center;
  }
}

/* 必须选择提示 */
.required-hint {
  color: #dc3545;
  font-size: 12px;
  font-weight: bold;
  margin-left: var(--spacing-xs);
}

.required-mark {
  color: #dc3545;
  font-weight: bold;
  margin-left: var(--spacing-xs);
}

.selection-hint {
  color: var(--text-light);
  font-style: italic;
  text-align: center;
  margin-bottom: var(--spacing-md);
  padding: var(--spacing-sm);
  background: #f8f9fa;
  border-radius: var(--border-radius);
  border-left: 4px solid #ffc107;
}

/* 自定义确认对话框 */
.confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.confirm-dialog {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  width: 90%;
  max-width: 480px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
  animation: slideUp 0.3s ease-out;
  overflow: hidden;
}

@keyframes slideUp {
  from {
    transform: translateY(30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.confirm-header {
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.confirm-header h3 {
  margin: 0;
  color: white;
  font-size: 22px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.confirm-body {
  padding: 24px;
  background: white;
}

.confirm-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.confirm-label {
  font-weight: 600;
  color: #2d3748;
  font-size: 14px;
}

.confirm-value {
  font-weight: 700;
  color: #667eea;
  font-size: 15px;
}

.confirm-warning {
  margin-top: 20px;
  padding: 16px;
  background: linear-gradient(135deg, #fff5e6 0%, #ffe4cc 100%);
  border-radius: 8px;
  border-left: 4px solid #ff9800;
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.warning-icon {
  font-size: 24px;
  flex-shrink: 0;
}

.warning-text {
  color: #d84315;
  font-size: 13px;
  line-height: 1.6;
  font-weight: 500;
}

.confirm-question {
  margin-top: 20px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.confirm-footer {
  padding: 16px 24px;
  background: #f8f9fa;
  display: flex;
  gap: 12px;
  justify-content: center;
  border-top: 1px solid #e2e8f0;
}

.confirm-footer .btn {
  min-width: 120px;
  padding: 12px 24px;
  font-size: 15px;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.confirm-footer .btn-success {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.confirm-footer .btn-success:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}

.confirm-footer .btn-secondary {
  background: #e2e8f0;
  color: #4a5568;
  border: none;
}

.confirm-footer .btn-secondary:hover {
  background: #cbd5e0;
  transform: translateY(-2px);
}

/* 响应式 */
@media (max-width: 768px) {
  .confirm-dialog {
    width: 95%;
    max-width: none;
  }

  .confirm-header h3 {
    font-size: 18px;
  }

  .confirm-body {
    padding: 16px;
  }

  .confirm-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .confirm-footer .btn {
    min-width: 100px;
    padding: 10px 20px;
    font-size: 14px;
  }
}
</style>
